﻿using IdentityModel;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Mappers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ConfigurationDbContext = Devonline.Identity.Admin.Models.ConfigurationDbContext;

namespace Devonline.Identity.Admin.Controllers;

/// <summary>
/// 接口管理
/// </summary>
[Route("api/[controller]")]
[ApiController]
[SecurityHeaders]
[Authorize(Roles = GROUP_MAINTAINERS)]
public class ApisController : ControllerBase
{
    private readonly AdminSetting _appSetting;
    private readonly ConfigurationDbContext _dbContext;
    private readonly PersistedGrantDbContext _persistedGrantDbContext;
    private readonly ILogger<ApisController> _logger;

    public ApisController(
        AdminSetting appSetting,
        ConfigurationDbContext dbContext,
        PersistedGrantDbContext persistedGrantDbContext,
        ILogger<ApisController> logger)
    {
        _appSetting = appSetting;
        _dbContext = dbContext;
        _persistedGrantDbContext = persistedGrantDbContext;
        _logger = logger;
    }

    [AllowAnonymous, HttpGet("Init")]
    public async Task<IActionResult> InitIdentityData()
    {
        await _dbContext.AutoMigrationAsync();
        await _persistedGrantDbContext.AutoMigrationAsync();
        _logger.LogInformation("数据迁移完成!");

        var json = System.IO.File.ReadAllText("identityServerData.json");
        if (string.IsNullOrWhiteSpace(json))
        {
            return BadRequest("identityServerData.json文件不存在");
        }

        var identityServerData = json.ToJsonObject<IdentityServerData>();

        #region IdentityResource
        var identityResources = await _dbContext.IdentityResources.ToListAsync();
        if (identityResources.IsNotNullOrEmpty())
        {
            _dbContext.IdentityResources.RemoveRange(identityResources);
        }

        foreach (var resource in identityServerData.IdentityResources)
        {
            await _dbContext.IdentityResources.AddAsync(resource.ToEntity());
        }
        #endregion

        #region ApiScope
        var apiScopes = await _dbContext.ApiScopes.ToListAsync();
        if (apiScopes.IsNotNullOrEmpty())
        {
            _dbContext.ApiScopes.RemoveRange(apiScopes);
        }

        foreach (var apiScope in identityServerData.ApiScopes)
        {
            await _dbContext.ApiScopes.AddAsync(apiScope.ToEntity());
        }
        #endregion

        #region ApiResource
        var apiResources = await _dbContext.ApiResources.ToListAsync();
        if (apiResources.IsNotNullOrEmpty())
        {
            _dbContext.ApiResources.RemoveRange(apiResources);
        }

        foreach (var resource in identityServerData.ApiResources)
        {
            resource.ApiSecrets.Add(new IdentityServer4.Models.Secret(_appSetting.DefaultPassword.ToSha256()));
            await _dbContext.ApiResources.AddAsync(resource.ToEntity());
        }
        #endregion

        #region Client
        var clients = await _dbContext.Clients.ToListAsync();
        if (clients.IsNotNullOrEmpty())
        {
            _dbContext.Clients.RemoveRange(clients);
        }

        foreach (var client in identityServerData.Clients)
        {
            client.ClientSecrets.Add(new IdentityServer4.Models.Secret(_appSetting.DefaultPassword.ToSha256()));
            //client.Claims = client.Claims.Select(c => new ClientClaim(c.Type, c.Value)).ToList();
            await _dbContext.Clients.AddAsync(client.ToEntity());
        }
        #endregion

        await _dbContext.SaveChangesAsync();
        return Ok();
    }
}